package com.dhruvtaara.beta.toolset;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class EmailClient {

	private static final AppLog logger = new AppLog(
			DefaultEncryption.class.getName());

	/**
	 * 
	 * @param sender
	 * @param senderDisplayname
	 * @param recipients
	 * @param message
	 * @param subject
	 */
	public void Send(String sender, String senderDisplayname,
			List<String> recipients, String message, String subject) {

		Properties properties = new Properties();
		Session session = Session.getDefaultInstance(properties, null);

		try {
			Message email = new MimeMessage(session);
			email.setFrom(new InternetAddress(sender, senderDisplayname));
			addRecipients(recipients, email);
			email.setSubject(subject);
			email.setText(message);
			Transport.send(email);
		} catch (UnsupportedEncodingException ex) {
			logger.Error(String.format(
					"Failed to send mail, addresses [{0}] [{1}] error: [{2}]",
					sender, recipients.get(0), ex.getMessage()));
		} catch (AddressException ex) {
			logger.Error(String
					.format("Failed to send mail, invalid address [{0}] [{1}] error: [{2}]",
							sender, recipients.get(0), ex.getMessage()));
		} catch (MessagingException ex) {
			logger.Error(String.format(
					"Failed to send mail, addresses [{0}] [{1}] error: [{2}]",
					sender, recipients.get(0), ex.getMessage()));
		}
	}

	/**
	 * 
	 * @param recipient
	 * @param email
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException
	 */
	protected void addRecipients(List<String> recipients, Message email)
			throws MessagingException, UnsupportedEncodingException {
		for (String recipient : recipients) {
			email.addRecipient(Message.RecipientType.TO, new InternetAddress(
					recipient, recipient));
		}
	}
}
